<template>
  <el-dialog v-model="dialogVisible" title="批量上传" width="500px">
    <el-form :model="uploadForm" label-width="100px">
      <el-form-item label="选择项目">
        <el-select
          clearable
          v-model="uploadForm.proidstr"
          placeholder="请选择项目"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.proname"
            :value="item.proidstr"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传文件">
        <shpupload
          ref="uploadRef"
          :map="useBasemap.basemap"
          @flytoshp="flytoshp"
          @shploaded="shploaded"
          @removelayer="removelayer"
        >
        </shpupload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref,watch, defineProps, defineEmits, computed } from "vue";
import shpupload from "@/components/shpupload/index.vue";
import { useBasemapStore } from "@/stores/basemapStore";
import request from "@/utils/request";
import { ElMessage, ElLoading } from "element-plus";
const useBasemap = useBasemapStore();

const props = defineProps({
  modelValue: Boolean,
  projectList: Array,
});

const emit = defineEmits(["update:modelValue"]);
const uploadForm = ref({});

/* 地图逻辑是这样按照图层进行组织：
map
- 上传图层 用来显示上传的文件预览数据
- 项目图层 用于显示项目点线面数据
- 行政区图层 用来显示行政区的点数据
这里的上传组件就是在上传图层里进行增加修改的

但是这样就引申出一个问题，就是最终上传完的数据保存后需要清除，也就是清空上传图层
再进入这个区或者工程，才会将数据添加至项目图层中

所以有三个建议：
1. 上传组件不设置突出显示，可以操作地图浏览上传的数据；
2. 确定和点击之后，需要调用uploadRef.value.clearAll()清空方法清空上传图层；
3. 其他组件调用时，尤其时工程图层中对点线面进行点击时，需要补充更多信息，例如关联的工程信息id之类的，可以考虑从最终的geojson中的features=>properties遍历添加object，
或者传值在组件内onEachFeature中{}中补充（第二种方法不建议，万一先传shp的时候没选项目，就无法关联了）。

*/
const uploadRef = ref();

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    uploadRef.value.clearAll();
    uploadRef.value.clearfilelist();
  }
});
let currentGemo = null;
const shploaded = (gemo) => {
  // console.log(gemo);
  window.clearProject();
  currentGemo = gemo;
};
const removelayer = () => {
  currentGemo = null;
};
const flytoshp = (extent) => {
  window.flytoshp(extent);
};

const loadingInstance = ref(null);

const handleCancel = () => {
  console.log('取消')
  dialogVisible.value = false;
  uploadRef.value.clearAll();
  uploadRef.value.clearfilelist();
};

const handleConfirm = async () => {
  if (!uploadForm.value.proidstr || !currentGemo) {
    ElMessage({
      message: "请选择项目和文件！",
      type: "warning",
    });
    return;
  }

  const currentProject = props.projectList.find(
    (item) => item.proidstr === uploadForm.value.proidstr
  );
  console.log(props.projectList, uploadForm.value.proidstr);

  loadingInstance.value = ElLoading.service({
    lock: true,
    text: "正在上传...",
    spinner: "el-icon-loading",
    background: "rgba(255, 255, 255, 0.7)",
  });

  try {
    currentGemo["geojson"]['features'].forEach((item) => {  
      item.properties.project = currentProject
    })
    const { data } = await request.post("/zhsj/api/saveslsj", {
      name: currentProject.proname,
      city: currentProject.proshiName,
      xzq: currentProject.prodqName,
      filename: currentGemo["filename"],
      gemo: JSON.stringify(currentGemo["geojson"]),
    });

    ElMessage({
      message: "上传成功！",
      type: "success",
    });
    dialogVisible.value = false;

    // 清除图层
    uploadRef.value.clearAll();
  } catch (error) {
    console.log(error);
    ElMessage({
      message: "上传失败，请重试。",
      type: "error",
    });
  } finally {
    loadingInstance.value.close();
  }
};
</script>
